import React from 'react';
import { Navigate } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext';

// ProtectedRoute组件，用于保护需要特定角色访问的路由
// children: 要渲染的子组件
// requiredRole: 访问该路由所需的角色或角色数组 (例如："ROLE_ADMIN", ["ROLE_USER", "ROLE_DOCTOR"])
const ProtectedRoute = ({ children, requiredRole }) => {
  const { currentUser, isAuthenticated, loading } = useAuth(); // Added loading state

  // Display a loading indicator while auth state is being determined
  if (loading) {
    return <div>Loading authentication status...</div>; // Or a spinner component
  }
  
  // 如果用户未登录，重定向到登录页面
  if (!isAuthenticated) {
    console.log('ProtectedRoute: Not authenticated, redirecting to /login');
    return <Navigate to="/login" replace />;
  }
  
  // 检查角色
  if (requiredRole) {
    const userRoles = currentUser.roles || [];
    let hasRequiredRole = false;

    if (Array.isArray(requiredRole)) {
      // 如果 requiredRole 是一个数组，检查用户是否拥有其中任何一个角色
      hasRequiredRole = requiredRole.some(role => userRoles.includes(role));
    } else {
      // 如果 requiredRole 是一个字符串，直接检查
      hasRequiredRole = userRoles.includes(requiredRole);
    }

    if (!hasRequiredRole) {
      console.log(`ProtectedRoute: User roles (${userRoles.join(', ')}) do not meet required roles (${Array.isArray(requiredRole) ? requiredRole.join(' or ') : requiredRole}), redirecting to /`);
      return <Navigate to="/" replace />;
    }
  }
  
  // 用户已登录并拥有所需角色（或路由不需要特定角色），允许访问路由
  return children;
};

export default ProtectedRoute; 